<template>
  <div>
    
      <!-- <el-button type="primary" @click="showUploadDialog">上传简历</el-button> -->
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="简历编号">
          <el-input 
            v-model="filterForm.resId" 
            placeholder="请输入简历编号" 
            clearable
            @keyup.enter="handleFilter"
          />
        </el-form-item>
        <el-form-item label="简历名称">
          <el-input 
            v-model="filterForm.resFileName" 
            placeholder="请输入简历名称" 
            clearable
            @keyup.enter="handleFilter"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
           <el-button type="primary" @click="showUploadDialog">上传简历</el-button>
        </el-form-item>
      </el-form>
    
    
    
      <el-table border :data="resumeList" style="width: 100%" v-loading="loading" :row-class-name="tableRowClassName">
        <el-table-column prop="resId" label="简历编号" width="80" sortable></el-table-column>
        <el-table-column prop="stuId" label="学生编号" width="100" sortable></el-table-column>
        <el-table-column prop="resExperienceYear" label="工作经验(年)" width="120" sortable></el-table-column>
        <el-table-column prop="resFileName" label="简历文件名" sortable>
          <template #default="scope">
            <el-tooltip :content="scope.row.resFileName" placement="top">
              <el-link 
                type="primary" 
                :underline="false"
                @click="openPdfDirectly(scope.row)"
              >
                {{ truncateFileName(scope.row.resFileName) }}
              </el-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="resPath" label="简历路径" show-overflow-tooltip></el-table-column>
        <el-table-column prop="resUpload" label="上传时间" width="170" sortable>
          <template #default="scope">
            {{ formatDateTime(scope.row.resUpload) }}
          </template>
        </el-table-column>
        <el-table-column prop="resStatus" label="状态" width="100">
          <template #default="scope">
           
              {{ scope.row.resStatus ? '合格' : '不合格' }}
          
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="danger" @click="confirmDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="mt-4"
      />
    

    <!-- 上传简历对话框 -->
    <el-dialog 
      title="批量上传简历" 
      v-model="uploadDialogVisible" 
      width="700px"
      :close-on-click-modal="false"
    >
      <el-alert
        title="文件名格式要求：学生ID-岗位-工作经验-姓名.pdf（如：1-Java-5年-张大科.pdf）"
        type="info"
        show-icon
        class="mb-4"
      />
      
      <el-form 
        ref="uploadFormRef" 
        :model="uploadForm" 
        label-width="120px"
      >
        <el-form-item label="简历文件" required>
          <el-upload
            class="upload-demo"
            drag
            multiple
            action="#"
            :auto-upload="false"
            :limit="10"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="uploadForm.fileList"
            accept=".pdf"
            :before-upload="beforeUpload"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将PDF文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                仅支持PDF格式文件，每个文件不超过5MB，最多10个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="解析预览" v-if="uploadForm.fileList.length > 0">
          <el-table :data="filePreviewData" border style="width: 100%">
            <el-table-column prop="fileName" label="文件名" width="180"></el-table-column>
            <el-table-column prop="position" label="岗位"></el-table-column>
            <el-table-column prop="experience" label="工作经验"></el-table-column>
            <el-table-column prop="studentName" label="学生姓名"></el-table-column>
            <el-table-column prop="stuId" label="学生ID"></el-table-column>

            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.isValid ? 'success' : 'danger'">
                  {{ scope.row.isValid ? '有效' : '格式不符' }}
                </el-tag>
                <span v-if="!scope.row.isValid" class="ml-2 text-gray-500">
                  ({{ scope.row.errorMsg }})
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitUpload" 
          :loading="uploading"
          :disabled="!canUpload"
        >
          确认上传 ({{ validFileCount }}个有效文件)
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { uploadResumeApi, getResumeListApi, deleteResumeApi } from '@/api/stu-api'

// 简历列表数据
const resumeList = ref([])
const loading = ref(false)

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选表单数据
const filterForm = reactive({
  resId: '',
  resFileName: ''
})

// 上传对话框相关
const uploadDialogVisible = ref(false)
const uploadFormRef = ref(null)
const uploading = ref(false)

// 上传表单数据
const uploadForm = reactive({
  fileList: [],
  files: []
})

// 文件名解析预览数据
const filePreviewData = computed(() => {
  return uploadForm.files.map((file: File) => {
    if (file.type !== 'application/pdf') {
      return {
        fileName: file.name,
        isValid: false,
        errorMsg: '非PDF文件'
      }
    }
    
    const parsedInfo = parseFileName(file.name)
    return {
      fileName: file.name,
      ...parsedInfo,
      isValid: parsedInfo.isValid,
      errorMsg: parsedInfo.errorMsg || ''
    }
  })
})

// 有效文件数量
const validFileCount = computed(() => {
  return filePreviewData.value.filter(item => item.isValid).length
})

// 是否可以上传
const canUpload = computed(() => {
  return validFileCount.value > 0
})

// 获取简历列表
const fetchResumeList = async () => {
  try {
    loading.value = true
    const params = <any>{
      page: currentPage.value,
      size: pageSize.value,
      ...filterForm
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '') {
        delete params[key]
      }
    })
    
    const response = await getResumeListApi(params)
    resumeList.value = response.data.list
    total.value = response.data.total
  } catch (error:any) {
    ElMessage.error('获取简历列表失败: ' + (error.message || ''))
    console.error('获取简历列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchResumeList()
}

// 重置筛选
const resetFilter = () => {
  filterForm.resId = ''
  filterForm.resFileName = ''
  currentPage.value = 1
  fetchResumeList()
}

// 直接在新窗口打开PDF
const openPdfDirectly = (resume:any) => {
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/'
  const pdfUrl = resume.resPath.startsWith('http') 
    ? resume.resPath 
    : `${baseUrl}${resume.resPath}`
  
  window.open(pdfUrl, '_blank')
}

// 截断过长的文件名
const truncateFileName = (fileName:any) => {
  if (fileName.length > 20) {
    return fileName.substring(0, 15) + '...' + fileName.split('.').pop()
  }
  return fileName
}

// 格式化日期时间
const formatDateTime = (date:any) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

// 解析文件名
const parseFileName = (fileName:any) => {
  if (!fileName.toLowerCase().endsWith('.pdf')) {
    return {
      stuId: null,
      position: '',
      experience: '',
      experienceYears: 0,
      studentName: '',
      isValid: false,
      errorMsg: '文件扩展名必须为.pdf'
    }
  }

  const basename = fileName.replace(/\.pdf$/i, "")
  const parts = basename.split('-')
  
  if (parts.length >= 4) {
    const stuId = parts[0]
    const position = parts[1]
    const experience = parts[2]
    const studentName = parts.slice(3).join('-')
    
    if (!/^\d+$/.test(stuId)) {
      return {
        stuId: null,
        position,
        experience,
        experienceYears: 0,
        studentName,
        isValid: false,
        errorMsg: '学生ID必须为数字'
      }
    }
    
    const experienceYears = extractYears(experience)
    
    return {
      stuId: parseInt(stuId),
      position,
      experience: experienceYears ? `${experienceYears}年` : experience,
      experienceYears: experienceYears || 0,
      studentName,
      isValid: true
    }
  }
  
  return {
    stuId: null,
    position: '',
    experience: '',
    experienceYears: 0,
    studentName: '',
    isValid: false,
    errorMsg: '文件名格式不正确'
  }
}

// 从字符串中提取年份数字
const extractYears = (str:any) => {
  const match = str.match(/\d+/)
  return match ? parseInt(match[0]) : null
}

// 显示上传对话框
const showUploadDialog = () => {
  uploadDialogVisible.value = true
  resetUploadForm()
}

// 重置上传表单
const resetUploadForm = () => {
  uploadForm.fileList = []
  uploadForm.files = []
}

// 上传前的验证
const beforeUpload = (file:any) => {
  const isPDF = file.type === 'application/pdf'
  const isLt5M = file.size / 1024 / 1024 < 5
  
  if (!isPDF) {
    ElMessage.error(`${file.name} 不是PDF文件!`)
    return false
  }
  
  if (!isLt5M) {
    ElMessage.error(`${file.name} 大小不能超过5MB!`)
    return false
  }
  
  return true
}

// 文件变化处理
const handleFileChange = (file:any, fileList:any) => {
  if (beforeUpload(file.raw)) {
    uploadForm.fileList = fileList
    uploadForm.files = fileList.map((item:any) => item.raw)
  } else {
    uploadForm.fileList = uploadForm.fileList.filter((item:any) => item.uid !== file.uid)
  }
}

// 文件移除处理
const handleFileRemove = (file:any, fileList:any) => {
  file
  uploadForm.fileList = fileList
  uploadForm.files = fileList.map((item:any) => item.raw)
}

// 提交上传
const submitUpload = async () => {
  try {
    uploading.value = true
    
    // 筛选有效文件
    const validFiles = uploadForm.files.filter((file, index) => {
      return filePreviewData.value[index].isValid
    })
    
    if (validFiles.length === 0) {
      ElMessage.error('没有有效的文件可以上传')
      return
    }
    
    const formData = new FormData()
    
    validFiles.forEach(file => {
      formData.append('files', file)
    })
    
    const response = await uploadResumeApi(formData)
    
    if (response.code === 200) {
      ElMessage.success(response.msg || `成功上传 ${validFiles.length} 个文件`)
      uploadDialogVisible.value = false
      fetchResumeList()
    } else {
      ElMessage.error(response.msg || '上传失败')
    }
  } catch (error:any) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败: ' + (error.message || '请检查文件'))
  } finally {
    uploading.value = false
  }
}

// 确认删除
const confirmDelete = (row:any) => {
  ElMessageBox.confirm(
    `确定要删除学生 ${row.studentName || row.stuId} 的简历吗?`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteResumeApi(row.resId)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchResumeList()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 分页大小变化处理
const handleSizeChange = (newPageSize:any) => {
  pageSize.value = newPageSize
  fetchResumeList()
}

// 当前页变化处理
const handleCurrentChange = (newPage:any) => {
  currentPage.value = newPage
  fetchResumeList()
}


// 初始化加载数据
onMounted(() => {
  fetchResumeList()
});

// 表格行样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  row
  if (rowIndex % 2 === 0) {
    return 'success-row'
  }
  return ''
}

</script>

<style scoped>

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

.filter-form {
  margin-left: 20px;
}

.upload-demo {
  width: 100%;
}

.el-table {
  margin-top: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}

.mb-4 {
  margin-bottom: 1rem;
}

.ml-2 {
  margin-left: 0.5rem;
}

.text-gray-500 {
  color: #6b7280;
}

.el-link {
  text-decoration: none;
}
</style>